﻿using System;
using System.Web;
using System.Web.Caching;
using log4net;

namespace CWB.Common.Utilities
{
    public static class OutputCacheExpiryHelper
    {
        public static readonly string CACHE_DEPENDENCY_KEY = "CachePages";
        static readonly ILog log = LogManager.GetLogger(typeof(OutputCacheExpiryHelper).Name);

        // Calling this method will expire all output cacheed pages that are dependent of CACHE_DEPENDENCY_KEY
        public static void UpdateDependentItem(DateTime value)
        {
            HttpRuntime.Cache.Insert(CACHE_DEPENDENCY_KEY, value, null,
                DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.NotRemovable,
                (key, val, reason) =>
                {
                    log.DebugFormat("{0} is removed from Cache. Reason: {1}", key, reason);
                });
        }

        public static void AddDependency(HttpContextBase contextbase)
        {
            if (HttpRuntime.Cache[CACHE_DEPENDENCY_KEY] == null)
            {
                UpdateDependentItem(DateTime.Now);
            }

            contextbase.Response.AddCacheItemDependency(CACHE_DEPENDENCY_KEY);
        }
    }
}
